// 格式化选项
interface FormatOptions {
  week?: boolean
  client?: boolean
}

/**
 * 格式化时间
 *
 * @param timestamp 时间戳
 * @param format 时间格式
 * @param options 格式化选项
 * @returns 返回格式化后的时间字符串
 */
function formatTime(timestamp: number, format: string, options: FormatOptions = {}): string {
  const date = new Date(timestamp)
  const { week, client } = options

  const weekdays: string[] = ['日', '一', '二', '三', '四', '五', '六']

  // 补零函数，用于补齐单个数字前的0
  const padZero = (num: number): string => (num < 10 ? '0' + num : num.toString())

  const Y = date.getFullYear()
  const M = padZero(date.getMonth() + 1)
  const D = padZero(date.getDate())
  const h = padZero(date.getHours())
  const m = padZero(date.getMinutes())
  const s = padZero(date.getSeconds())
  const dayOfWeek = week ? weekdays[date.getDay()] : ''

  // 时间格式化
  const formattedDate = format
    .replace(/Y/g, Y.toString())
    .replace(/M/g, M)
    .replace(/D/g, D)
    .replace(/h/g, h)
    .replace(/m/g, m)
    .replace(/s/g, s)

  const result = week ? `${formattedDate} 星期${dayOfWeek}` : formattedDate

  // 客户端模式
  if (client) {
    const now = Date.now()
    const diff = Math.floor((now - date.getTime()) / 1000)

    if (diff < 0) return result

    if (diff < 1800) {
      return '1分钟前'
    } else if (diff < 3600) {
      return '30分钟前'
    } else if (diff < 5400) {
      return '1个小时前'
    } else {
      return result
    }
  }

  return result
}

export default formatTime
